package com.originskyseed.platform.cms.service.impl;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.cms.mapper.CmsMapper;
import com.originskyseed.platform.cms.mapper.CmsRelateIsReadMapper;
import com.originskyseed.platform.cms.mapper.CmsRelateViewMapper;
import com.originskyseed.platform.cms.model.Cms;
import com.originskyseed.platform.cms.model.CmsRelateIsRead;
import com.originskyseed.platform.cms.model.CmsRelateView;
import com.originskyseed.platform.cms.service.ICmsService;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.mapper.DeptMapper;
import com.originskyseed.platform.user.mapper.ParameterConfigureMapper;
import com.originskyseed.platform.user.mapper.UserInfoMapper;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.ParameterConfigure;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 新闻表Service接口实现类（OSI_CMS）
 *
 * @author wlj
 */
@DubboService
@Component("cmsService")
public class CmsServiceImpl implements ICmsService {

    @Resource
    private CmsMapper cmsMapper;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private CmsRelateViewMapper cmsRelateViewMapper;

    @Resource
    private CmsRelateIsReadMapper cmsRelateIsReadMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private ParameterConfigureMapper parameterConfigureMapper;

    /**
     * 删除记录
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public int deleteByPrimaryKey(String id) throws Exception {
        return this.cmsMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除记录
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Override
    public int deleteByPrimaryKeys(List<String> ids) throws Exception {
        return this.cmsMapper.deleteByPrimaryKeys(ids);
    }

    /**
     * 插入记录
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int insert(Cms record) throws Exception {
        if (StringUtils.isBlank(record.getId())) {
            record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
        }
        record.setCreateTime(new Date());
        return this.cmsMapper.insert(record);
    }

    /**
     * 批量插入
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public int insertBatchTenantCode(List<Cms> list, String tenantCode) throws Exception {
        if (StringUtils.isNotEmpty(tenantCode)) {
            TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
        }
        return this.insertBatch(list);
    }

    /**
     * 批量插入
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public int insertBatch(List<Cms> list) throws Exception {
        return this.cmsMapper.insertBatch(list);
    }

    /**
     * 插入记录（仅非空值字段）
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int insertSelective(Cms record) throws Exception {
        if (StringUtils.isBlank(record.getId())) {
            record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
        }
        record.setCreateTime(new Date());
        return this.cmsMapper.insertSelective(record);
    }

    /**
     * 新增新闻/通知公告
     *
     * @param cms
     * @param userInfo
     * @return
     * @throws Exception
     */
    @Override
    public int insertCmsSelective(Cms cms, UserInfo userInfo) throws Exception {
        if (cms.getType() != null && cms.getBelongPlatform() != null) {
            //新增
            String primaryKey = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
            cms.setId(primaryKey);
            cms.setCreator(userInfo.getName());
            cms.setCreatorId(userInfo.getId());
            cms.setState(3);//发布
            cms.setIsDel(2);
            cms.setIsTop(0);
            cms.setVisitorCount(0);
            //cms.setBelongPlatform(num);
            cms.setCreateTime(new Date());
            Integer prority = this.cmsMapper.selectPrority();
            if (prority == null) {
                cms.setPrority(0);
            } else {
                cms.setPrority(prority + 1);
            }
            this.cmsMapper.insertSelective(cms);
            List<UserInfo> userInfoList = new ArrayList<>();
            //批量插入阅读情况表
            List<CmsRelateIsRead> list = new ArrayList<>();

            if (cms.getType() == 1) { // 新闻
                String belongPlatform = cms.getBelongPlatform();
                List<String> platForm = Arrays.asList(belongPlatform.split(","));
                if (platForm != null && platForm.size() > 0) {
                    for (String num : platForm) {
                        if (num.equals("1")) {
                            List<UserInfo> userInfos1 = this.selectUser(1);
                            if (userInfos1 != null && userInfos1.size() > 0) {
                                for (UserInfo info : userInfos1) {
                                    userInfoList.add(info);
                                }
                            }
                        } else if (num.equals("2")) {
                            List<UserInfo> userInfos1 = this.selectUser(2);
                            if (userInfos1 != null && userInfos1.size() > 0) {
                                for (UserInfo info : userInfos1) {
                                    userInfoList.add(info);
                                }
                            }
                        } else {
                            List<UserInfo> userInfos1 = this.selectUser(0);
                            if (userInfos1 != null && userInfos1.size() > 0) {
                                for (UserInfo info : userInfos1) {
                                    userInfoList.add(info);
                                }
                            }
                        }
                    }
                }
            }
            //通知公告
            if (cms.getType() == 2) {
                //获取查看范围部门
                if (cms.getObjDeptId() != null) {
                    String objDeptId = cms.getObjDeptId();
                    List<String> deptId = Arrays.asList(objDeptId.split(","));
                    //查询部门人员
                    if (deptId != null && deptId.size() > 0) {
                        for (String s : deptId) {
                            if (cms.getObjType() == 3) { // 岗位
                                ParameterConfigure parameterConfigure = this.parameterConfigureMapper.selectByPrimaryKey(cms.getObjDeptId());
                                if (parameterConfigure != null) {
                                    //通过type查询用户
                                    userInfoList = this.userInfoMapper.selectByType(Integer.valueOf(parameterConfigure.getCode()));
                                    CmsRelateView relateView = new CmsRelateView();
                                    String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
                                    relateView.setId(key);
                                    relateView.setCmsId(primaryKey);
                                    relateView.setObjId(cms.getObjDeptId());
                                    relateView.setObjName(parameterConfigure.getName());
                                    relateView.setCreateTime(new Date());
                                    this.cmsRelateViewMapper.insertSelective(relateView);
                                }

                            } else {
                                //查询部门名称
                                Dept dept = this.deptMapper.selectByPrimaryKey(s);
                                if (dept != null) {
                                    //关联查看范围对象
                                    CmsRelateView relateView = new CmsRelateView();
                                    String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
                                    relateView.setId(key);
                                    relateView.setCmsId(primaryKey);
                                    relateView.setObjId(s);
                                    relateView.setObjName(dept.getName());
                                    relateView.setCreateTime(new Date());
                                    this.cmsRelateViewMapper.insertSelective(relateView);
                                }
                                //查询体系下的人员
                                Dept dept1 = this.deptMapper.selectByPrimaryKey(s);
                                List<String> deptIdList = new ArrayList<>();
                                if (dept1 != null) {
                                    if (dept1.getType() == 3 || dept1.getType() == 5) { //小组
                                        deptIdList.add(dept1.getId());
                                    } else {
                                        this.selectSonId(dept1.getCode(), deptIdList);
                                    }
                                }
                                if (deptIdList != null && deptIdList.size() > 0) {
                                    userInfoList = this.userInfoMapper.selectUserInfoByDeptIds(deptIdList);
                                }
                            }
                        }
                    }
                } else { //全部人员
                    userInfoList = this.selectUser(3);
                }
            }
            //关联查看对象是否阅读
            if (userInfoList != null && userInfoList.size() > 0) {
                for (UserInfo info : userInfoList) {
                    String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
                    CmsRelateIsRead relateIsRead = new CmsRelateIsRead();
                    relateIsRead.setId(key);
                    relateIsRead.setCmsId(primaryKey);
                    relateIsRead.setId(key);
                    relateIsRead.setIsRead(2);
                    relateIsRead.setCreateTime(new Date());
                    relateIsRead.setObjId(info.getId());
                    relateIsRead.setObjName(info.getName());
                    list.add(relateIsRead);
                }
                //批量插入
                if (list != null && list.size() > 0) {
                    this.cmsRelateIsReadMapper.insertBatch(list);
                }
            }
        }
        return 1;
    }

    /**
     * 查询人员
     *
     * @param sys
     * @throws Exception
     */
    private List<UserInfo> selectUser(int sys) throws Exception {
        List<UserInfo> list = new ArrayList<>();
        UserInfo userInfo1 = new UserInfo();
        userInfo1.setIsDel(0);
        userInfo1.setStatus(1);
        if (sys == 0) {
            userInfo1.setSourceSys(0);
        } else if (sys == 1) {
            userInfo1.setSourceSys(1);
        } else if (sys == 2) {
            userInfo1.setSourceSys(2);
        }
        return this.userInfoMapper.selectList(userInfo1);
    }

    /**
     * 更新记录
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int updateByPrimaryKey(Cms record) throws Exception {
        record.setUpdateTime(new Date());
        return this.cmsMapper.updateByPrimaryKey(record);
    }

    /**
     * 更新记录（仅非空值字段）
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public int updateByPrimaryKeySelective(Cms record) throws Exception {
        record.setUpdateTime(new Date());
        return this.cmsMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 更新排序信息
     *
     * @param downCourse
     * @param upCourse
     * @return
     * @throws Exception
     */
    @Override
    public int updatePrority(Cms downCourse, Cms upCourse) throws Exception {
        downCourse.setUpdateTime(new Date());
        upCourse.setUpdateTime(new Date());
        this.cmsMapper.updateByPrimaryKeySelective(downCourse);
        return this.cmsMapper.updateByPrimaryKeySelective(upCourse);
    }

    /**
     * 更新是否置顶
     *
     * @param cms
     * @return
     * @throws Exception
     */
    @Override
    public int updateIsTop(Cms cms) throws Exception {
        cms.setUpdateTime(new Date());
        this.cmsMapper.updateIsTop(cms);
        return this.cmsMapper.updateByPrimaryKeySelective(cms);
    }

    /**
     * 查询最大有先级
     *
     * @return
     * @throws Exception
     */
    @Override
    public Integer selectPrority() throws Exception {
        return this.cmsMapper.selectPrority();
    }

    /**
     * 优先级定时任务
     *
     * @param tenantCode
     * @return
     * @throws Exception
     */
    @Override
    public Integer selectProrityTenantCode(String tenantCode) throws Exception {
        if (StringUtils.isNotEmpty(tenantCode)) {
            TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
        }
        return this.cmsMapper.selectPrority();
    }

    /**
     * 根据优先级查询新闻
     *
     * @return
     * @throws Exception
     */
    @Override
    public Cms selectCmsByPrority(Integer prority) throws Exception {
        return this.cmsMapper.selectCmsByPrority(prority);
    }

    /**
     * 阅读量统计
     *
     * @param cmsId
     * @return
     * @throws Exception
     */
    @Override
    public int updateVistorCount(String cmsId) throws Exception {
        return this.cmsMapper.updateVistorCount(cmsId);
    }

    /**
     * 新闻删除_假删除
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Override
    public int deleteNewsByIds(List<String> ids) throws Exception {
        return this.cmsMapper.deleteNewsByIds(ids);
    }

    /**
     * 新闻下架、发布
     *
     * @param ids
     * @param state
     * @return
     * @throws Exception
     */
    @Override
    public int updateNewsStateByIds(List<String> ids, int state) throws Exception {
        return this.cmsMapper.updateNewsStateByIds(ids, state);
    }

    /**
     * 通知公告发布后修改为已读状态
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Override
    public int updateInformStatusByIds(List<String> ids) throws Exception {
        return this.cmsMapper.updateInformStatusByIds(ids);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Cms selectByPrimaryKey(String id) throws Exception {
        return this.cmsMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询列表
     *
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public List<Cms> selectList(Cms record) throws Exception {
        return this.cmsMapper.selectList(record);
    }

    /**
     * 分页查询列表
     *
     * @param params
     * @param page
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Cms> selectListByPage(Map<String, Object> params, BasePage<Cms> page) throws Exception {
        params.put("page", page);
        List<Cms> list = this.cmsMapper.selectListByPage(params);
        page.setResults(list);
        return page;
    }

    /**
     * 推广平台_内容平台_分页查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Cms> selectListToGeneralizationByPage(Map<String, Object> params, BasePage<Cms> page, UserInfo userInfo) throws Exception {
        params.put("page", page);
        List<Cms> list = this.cmsMapper.selectListToGeneralizationByPage(params);
        page.setResults(list);
        return page;
    }

    /**
     * 小喇叭分页查询列表
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Cms> selectTrumpetListByPage(Map<String, Object> params, BasePage<Cms> page) throws Exception {
        SimpleDateFormat formatTimes = new SimpleDateFormat("yyyy-MM-dd");
        params.put("page", page);
        params.put("dateTime", formatTimes.format(new Date()));
        List<Cms> list = this.cmsMapper.selectTrumpetListByPage(params);
        page.setResults(list);
        return page;
    }

    /**
     * 开放平台_分页查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Cms> selectListToOpenPlatformByPage(Map<String, Object> params, BasePage<Cms> page) throws Exception {
        params.put("page", page);
        List<Cms> list = this.cmsMapper.selectListToOpenPlatformByPage(params);
        page.setResults(list);
        return page;
    }

    /**
     * 部门下的通知公告
     *
     * @param params
     * @param page
     * @return
     * @throws Exception
     */
    @Override
    public BasePage<Cms> selectDeptNoticeListByPage(Map<String, Object> params, BasePage<Cms> page) throws Exception {
        params.put("page", page);
        List<Cms> list = this.cmsMapper.selectDeptNoticeListByPage(params);
        page.setResults(list);
        return page;
    }

    /**
     * 查询组织下的部门
     *
     * @param code
     * @param list
     * @throws Exception
     */
    private void selectSonId(String code, List<String> list) throws Exception {
        List<Dept> deptList = this.deptMapper.selectByParentCode(code);
        if (deptList != null) {
            for (Dept dept1 : deptList) {
                list.add(dept1.getId());
                selectSonId(dept1.getCode(), list);
            }
        }
    }

    public BasePage<Cms> selectNoticeListByPage(Map<String, Object> params, BasePage<Cms> page) throws Exception {
        params.put("page", page);
        List<Cms> list = this.cmsMapper.selectNoticeListByPage(params);
        page.setResults(list);
        return page;
    }

    /**
     * 统计新闻未读
     *
     * @param params
     * @return
     * @throws Exception
     */
    public Integer countNewsReadObjNum(Map<String, Object> params) throws Exception{
        return this.cmsMapper.countNewsReadObjNum(params);
    }

    /**
     * 统计通知公告未读
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public Integer countCmsReadObjNum(Map<String, Object> params) throws Exception {
        return this.cmsMapper.countCmsReadObjNum(params);
    }

}
